package com.dormitory123.millet.web;

import com.dormitory123.millet.pojo.Cart;
import com.dormitory123.millet.pojo.Order;
import com.dormitory123.millet.pojo.OrderItem;
import com.dormitory123.millet.pojo.User;
import com.dormitory123.millet.service.Impl.OrderServiceImpl;
import com.dormitory123.millet.service.OrderService;
import com.dormitory123.millet.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yanhuanzhan
 * @date 2022/1/6 - 19:36
 */
public class OrderServlet extends BaseServlet{
  private OrderService orderService = new OrderServiceImpl();
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser == null) {
            resp.sendRedirect("/Millet/login.jsp");
            return;
        }
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart != null) {
            Order order=orderService.createOrder(cart,loginUser.getId());
            //保存最后一个订单的信息
            req.getSession().setAttribute("lastOrder",order);
        }

        //获取订单信息
        List<Order> orders = orderService.queryOrdersByUserId(loginUser.getId());

        if (orders.size() != 0) {
            Map<String, List<OrderItem>> orderItemMap = orderService.queryOrderItems(orders);
            //保存订单项map
            req.getSession().setAttribute("orderItemMap",orderItemMap);
        }
        //保存订单集合
        req.getSession().setAttribute("orders",orders);
        //保存订单个数
        req.getSession().setAttribute("orderCount",orders.size());
        cart.clear();//清空购物车
        req.getRequestDispatcher("/order_success.jsp").forward(req,resp);

    }
    protected void listOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser == null) {
            resp.sendRedirect("/Millet/login.jsp");
            return;
        }
        //获取订单信息
        List<Order> orders = orderService.queryOrdersByUserId(loginUser.getId());
        if (orders.size() != 0) {
            Map<String, List<OrderItem>> orderItemMap = orderService.queryOrderItems(orders);
            //保存订单项map
            req.getSession().setAttribute("orderItemMap",orderItemMap);
        }
        //保存订单集合
        req.getSession().setAttribute("orders",orders);
        //保存订单个数
        req.getSession().setAttribute("orderCount",orders.size());
        req.getRequestDispatcher("/myorder.jsp").forward(req,resp);
    }
}
